import openai

import telegram
from telegram import Chat, Update
from telegram.constants import ParseMode, ChatAction
from telegram.helpers import escape_markdown
import logging
import requests
from telegram.ext import (
    Application,
    CommandHandler,
    MessageHandler,
    filters, ConversationHandler, CallbackContext,
)

# 设置openai key
openai.api_key = ''
# 设置telegram bot token
telegram_token = ''

# Enable logging
logging.basicConfig(
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
logger = logging.getLogger(__name__)

# states
START, REPLY = range(2)


# 接收问题 返回结果
def retrunres(issue):
    completion = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[{"role": "user", "content": issue}]
    )
    print(completion)
    print(completion.choices[0].message.content)
    recontent = telegram.helpers.escape_markdown(completion.choices[0].message.content, 2)
    return recontent


# /start 开始
async def start(update: Update, context: CallbackContext) -> int:
    user_name = update.effective_user.full_name
    chat = update.effective_chat
    if chat.type != Chat.PRIVATE or chat.id in context.bot_data.get("user_ids", set()):
        return ConversationHandler.END

    logger.info("%s started a private chat with the bot", user_name)
    context.bot_data.setdefault("user_ids", set()).add(chat.id)

    # 发送文字
    await update.effective_message.reply_text(
        f"Welcome {user_name}. 我有什么能帮助您的？"
    )

    return REPLY


# 回复
async def reply(update: Update, context: CallbackContext) -> int:
    # 用户名
    user_name = update.effective_user.full_name
    # 获取用户发送的消息
    message_text = update.message.text
    # 获取被回复的消息
    reply_to_message = update.message.reply_to_message
    if reply_to_message and reply_to_message.text:
        # 获取被回复消息的文本内容
        previous_message_text = reply_to_message.text
        # 向用户发送"正在输入"状态
        await context.bot.send_chat_action(chat_id=update.effective_chat.id, action="typing")
        # 调用open ai
        Replycontent = await retrunres(previous_message_text + " " + message_text)
    else:
        # 向用户发送"正在输入"状态
        await context.bot.send_chat_action(chat_id=update.effective_chat.id, action="typing")
        # 如果没有被回复的消息，则只调用OpenAI
        Replycontent = retrunres(message_text)
    # 记录日志
    logger.info("Reply to %s %s", user_name, Replycontent)
    # 更新之前发送的等待提示消息
    await context.bot.send_message(chat_id=update.effective_chat.id, text=Replycontent,
                                   parse_mode=ParseMode.MARKDOWN_V2)
    # 发送回复 第3个参数 parse_mode=ParseMode.MARKDOWN_V2
    # await context.bot.send_message(chat_id=update.effective_chat.id, text=Replycontent)
    return REPLY


# /picture - 发送图片
async def pricture(update: Update, context: CallbackContext) -> None:
    # 发送提示
    await context.bot.send_message(chat_id=update.effective_chat.id,
                                   text="图片在来的路上...")
    # 发送“输入中”动作提示
    await context.bot.send_chat_action(chat_id=update.effective_chat.id, action=ChatAction.TYPING)
    # 请求图片接口
    prictureurl = requests.get('https://api.mtyqx.cn/tapi/random.php')
    # 提示上传
    await context.bot.send_chat_action(chat_id=update.effective_chat.id, action=ChatAction.UPLOAD_PHOTO)
    # 发送图片 prictureurl.url为图片的地址
    await context.bot.send_photo(update.effective_chat.id, prictureurl.url)


# /help - 发送本人电子邮件
async def help(update: Update, context: CallbackContext) -> None:
    await context.bot.send_message(chat_id=update.effective_chat.id,
                                   text="你可以发送邮件到我主人的邮箱.\nxyhghy@outlook.com")


# 处理/start 和 reply 状态之间的转换
def switch_to_reply(update: Update, context: CallbackContext) -> int:
    text = update.message.text
    if text and text.startswith("/") and text not in ["/start", "/help", "/picture"]:
        # 如果输入其他指令，则结束reply状态
        return None

    return REPLY


# 启动机器人
def main() -> None:
    # 创建应用程序并向其传递机器人的令牌.
    application = Application.builder().token(telegram_token).build()

    # Conversation handler
    conversation_handler = ConversationHandler(
        entry_points=[CommandHandler('start', start)],
        states={
            START: [],
            REPLY: [
                MessageHandler(filters.TEXT & ~filters.COMMAND & ~filters.Regex(r"^\s*$"), reply)
            ]
        },
        fallbacks=[],
        name="my_conversation",
    )

    # 添加conversation_handler
    application.add_handler(conversation_handler)

    # /picture
    application.add_handler(CommandHandler('picture', pricture))
    # /help
    application.add_handler(CommandHandler('help', help))
    # Run the bot until the user presses Ctrl-C
    # We pass 'allowed_updates' handle *all* updates including `chat_member` updates
    # To reset this, simply pass `allowed_updates=[]`
    application.run_polling(allowed_updates=Update.ALL_TYPES)


if __name__ == "__main__":
    main()
